package com.ybxx.core.command;

import com.ybxx.core.util.ParamUtil;
import com.ybxx.core.web.paging.PagingBean;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 功能：查询条件组合
 * 公司：XA.Co.LTD
 * 制作人：Tom.Y
 * 日期：2011-05*/
public class QueryFilter{
	public static final String ORDER_DESC = "desc";
	public static final String ORDER_ASC = "asc";
	public static final Log logger = LogFactory.getLog(QueryFilter.class);

	private HttpServletRequest request = null;
	private String filterName = null;
	private List<Object> paramValues = new ArrayList();
	private List<CriteriaCommand> commands = new ArrayList();
	private Set<String> aliasSet = new HashSet();
	private PagingBean pagingBean = null;
	
	public String getFilterName(){
		return this.filterName;
	}

	public void setFilterName(String filterName) {
		this.filterName = filterName;
	}
	
	public PagingBean getPagingBean(){
		return this.pagingBean;
	}

	public QueryFilter(HttpServletRequest request){
		this.request = request;
		Enumeration paramEnu = request.getParameterNames();
		while (paramEnu.hasMoreElements()) {
			String paramName = (String)paramEnu.nextElement();
			if (paramName.startsWith("Q_")) {
				String paramValue = request.getParameter(paramName);
				addFilter(paramName, paramValue);
			}
		}

		Integer start = Integer.valueOf(0);
		Integer limit = PagingBean.DEFAULT_PAGE_SIZE;

		String page = request.getParameter("page");
		String s_limit = request.getParameter("rows");
		if (StringUtils.isNotEmpty(s_limit)) {
			limit = new Integer(s_limit);
		}
		if (StringUtils.isNotEmpty(page)) {
			int cpage=Integer.parseInt(page);
			start = new Integer((cpage-1)*limit);
		}
		String sort = request.getParameter("sort");
		String dir = request.getParameter("order");

		if ((StringUtils.isNotEmpty(sort)) && (StringUtils.isNotEmpty(dir))) {
			addSorted(sort, dir);
		}

		this.pagingBean = new PagingBean(start.intValue(), limit.intValue());
	}

	public void addFilter(String paramName, String paramValue){
		String[] fieldInfo = paramName.split("[_]");
		Object value = null;
		if ((fieldInfo != null) && (fieldInfo.length == 4)) {
			value = ParamUtil.convertObject(fieldInfo[2], paramValue);
			if (value != null) {
				FieldCommandImpl fieldCommand = new FieldCommandImpl(fieldInfo[1], value, fieldInfo[3], this);
				this.commands.add(fieldCommand);
			}
		} else if ((fieldInfo != null) && (fieldInfo.length == 3)) {
			FieldCommandImpl fieldCommand = new FieldCommandImpl(fieldInfo[1], value, fieldInfo[2], this);
			this.commands.add(fieldCommand);
		} else {
			logger.error("Query param name [" + paramName + "] is not right format.");
		}
	}
	public String getWhere(){
		String swhere="";
		if(commands!=null && commands.size()>0){
			for(Iterator iter=commands.iterator();iter.hasNext();){
				try{
					FieldCommandImpl command = (FieldCommandImpl)iter.next();
					if(command!=null){
						if(command.getValue()!=null){
							if ("LT".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"<"+command.getValue()+" and ";
							else if ("GT".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+">"+command.getValue()+" and ";
							else if ("LE".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"<="+command.getValue()+" and ";
							else if ("GE".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+">="+command.getValue()+" and ";
							else if ("SLE".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"<='"+command.getValue()+"' and ";
							else if ("SGE".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+">='"+command.getValue()+"' and ";
							else if ("LK".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+" like '%"+command.getValue().toString().replaceAll(" ", "").replaceAll("'", ",")+"%' and ";
							else if ("LFK".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+" like '"+command.getValue().toString().replaceAll(" ", "").replaceAll("'", ",")+"%' and ";
							else if ("RHK".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+" like '%"+command.getValue().toString().replaceAll(" ", "").replaceAll("'", ",")+"' and ";
							else if ("NULL".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+" is null and ";
							else if ("NOTNULL".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+" is not null and ";
							else if ("EMP".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"='' and ";
							else if ("NOTEMP".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"!='' and ";
							else if ("NEQ".equals(command.getOperation()))
								swhere=swhere+command.getProperty()+"!='"+command.getValue()+"' and ";
							else if ("IN".equals(command.getOperation())){
								String v1 = "'"+command.getValue().toString().replaceAll(",", "','")+"'";
								swhere=swhere+command.getProperty()+" in ("+v1+") and ";
							}else if ("NIN".equals(command.getOperation())){
								String v1 = "'"+command.getValue().toString().replaceAll(",", "','")+"'";
								swhere=swhere+command.getProperty()+" not in ("+v1+") and ";
							}
							else{
								swhere=swhere+command.getProperty()+"='"+command.getValue()+"' and ";
							}
						}
					}
				}catch(Exception e){
					continue;
				}
				
				
			}
			if(StringUtils.isNotEmpty(swhere) && swhere.lastIndexOf("and")>0){
				swhere=swhere.substring(0,swhere.lastIndexOf("and"));
			}
			
		}
		if(swhere==null || swhere.equals("")){
			swhere=" 1=1 ";
		}
		return swhere;
	}
	public void addParamValue(Object value){
		this.paramValues.add(value);
	}

	public List getParamValueList() {
		return this.paramValues;
	}

	public void addSorted(String orderBy, String ascDesc) {
		this.commands.add(new SortCommandImpl(orderBy, ascDesc, this));
	}

	public void addExample(Object object) {
		this.commands.add(new ExampleCommandImpl(object));
	}

	public List<CriteriaCommand> getCommands() {
		return this.commands;
	}
	public Set<String> getAliasSet() {
		return this.aliasSet;
	}
}
